package file

import (
	"errors"
	"flow-calc/common"
	"flow-calc/core"
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
)

/**
 *    Description: 配置输出
 *    Date: 2024/4/2
 */

// ConfigExportYaml 配置导出
func ConfigExportYaml(flow core.Flow, savePath string) error {
	if data, err := yaml.Marshal(flow.GetConfig()); err != nil {
		return err
	} else {
		// flow 配置
		err = ioutil.WriteFile(savePath+common.FlowType+"-"+flow.GetName()+".yaml", data, 0644)
		if err != nil {
			return err
		}
		for _, fp := range flow.GetConfig().Flows {
			fConf := flow.GetFuncConfigByName(fp.FName)
			if fConf == nil {
				return errors.New(fmt.Sprintf("function name = %s config is nil ! ", fp.FName))
			}
			// function 配置
			if fData, err := yaml.Marshal(fConf); err != nil {
				return err
			} else {
				err = ioutil.WriteFile(savePath+common.FuncType+"-"+fConf.FName+".yaml", fData, 0644)
				if err != nil {
					return err
				}
			}
			// connector 配置
			if fConf.Option.CName != "" {
				conConf, err := fConf.GetConnConfig()
				if err != nil {
					return err
				}
				if conData, err := yaml.Marshal(conConf); err != nil {
					return err
				} else {
					err = ioutil.WriteFile(savePath+common.ConnectionType+"-"+conConf.Cname+".yaml", conData, 0644)
				}
			}
		}
	}
	return nil
}
